package com.iwunu.iot.common.util;


/**
 * 进制工具类
 * 
 * @author vivi207
 */
public class HexUtils {
	/**
     * 字节流转成十六进制表示
     */
    public static String encode(byte[] src) {
        String strHex = "";
        StringBuilder sb = new StringBuilder("");
        for (int n = 0; n < src.length; n++) {
            strHex = Integer.toHexString(src[n] & 0xFF);
            sb.append((strHex.length() == 1) ? "0" + strHex : strHex); // 每个字节由两个字符表示，位数不够，高位补0
        }
        return sb.toString().trim();
    }
    
    /**
     * 字符串转成字节流
     */
    public static byte[] decode(String src) {
        int m = 0, n = 0;
        int byteLen = src.length() / 2; // 每两个字符描述一个字节
        byte[] ret = new byte[byteLen];
        for (int i = 0; i < byteLen; i++) {
            m = i * 2 + 1;
            n = m + 1;
            int intVal = Integer.decode("0x" + src.substring(i * 2, m) + src.substring(m, n));
            ret[i] = Byte.valueOf((byte)intVal);
        }
        return ret;
    }
    /**
     * 字符IP加端口 转byte[]
     * @param src
     * @return
     */
    public static byte[]  stringIpTobyte06(String head,String length, String src){
    	if(src.length()!=6){
    		return null;
    	}
    	StringBuilder sb = new StringBuilder("");
    	sb.append(head).append(length);
		String [] str = src.split(":");
		String ip = str[0];
		String port = str[1];
		String ips[] = ip.split("\\.");
		for(String st :ips){
			 int intst = Integer.parseInt(st);
			 if(intst>16){
				 sb.append(Integer.toHexString(intst));
			 }else{
				 sb.append("0"+Integer.toHexString(intst));
			 }
		}
		sb.append(Integer.toHexString(Integer.parseInt(port)));
		return ByteTools.hexStringToBytes(sb.toString());
    }
    public static long ipToLong2(String ipAddress) {
    	 
		long result = 0;
 
		String[] ipAddressInArray = ipAddress.split("\\.");
 
		for (int i = 3; i >= 0; i--) {
 
			long ip = Long.parseLong(ipAddressInArray[3 - i]);
 
			// left shifting 24,16,8,0 and bitwise OR
 
			// 1. 192 << 24
			// 1. 168 << 16
			// 1. 1 << 8
			// 1. 2 << 0
			result |= ip << (i * 8);
 
		}
 
		return result;
	}
 

	/** 
     * 字符串转换为16进制字符串 
     *  
     * @param s 
     * @return 
     */  
    public static String stringToHexString(String s) {  
        String str = "";  
        for (int i = 0; i < s.length(); i++) {  
            int ch = s.charAt(i);  
            String s4 = Integer.toHexString(ch);  
            str = str + s4;  
        }  
        return str;  
    }
    /**
     * 字符2位 转byte[]
     * @param src
     * @return
     */
    public static byte[]  stringIpTobyte02(String head,String length, String src){
    	if(src.length()!=4){
    		return null;
    	}
    	StringBuilder sb = new StringBuilder("");
    	sb.append(head).append(length);
		String start = src.substring(0,1);
		String end = src.substring(2,4);
		sb.append(start).append(end);
		return ByteTools.hexStringToBytes(sb.toString());
    }
    /**
     * 字符1位 转byte[]
     * @param src
     * @return
     */
    public static byte[]  stringIpTobyte01(String head,String length, String src){
    	StringBuilder sb = new StringBuilder("");
    	sb.append(head).append(length);
		sb.append(src);
		return ByteTools.hexStringToBytes(sb.toString());
    }

    public static String toHex(int num,int length){
        char[] chs = new char[length];//定义容器，存储的是字符，长度为8.一个整数最多8个16进制数
        int index = chs.length-1;
        for(int i = 0;i<length;i++) {
            int temp = num & 15;

            if(temp > 9){
                chs[index] = ((char)(temp-10+'A'));
            }else {
                chs[index] = ((char)(temp+'0'));
            }

            index--;
            num = num >>> 4;
        }
        return toString(chs);
    }

    public static String toHexL(String data,int length){
    	try {
    	       String str = Long.toHexString(Long.valueOf(data)) ;
    	        if(str.length()<length){
    	            int size = str.length();
    	            for(int i=0;i<length-size;i++){
    	                str="0"+str ;
    	            }
    	        }
    	        return str;
		} catch (Exception e) {
			return data;
		}
    }


    public static String toString(char[] arr){
        String temp = "";
        for(int i = 0;i<arr.length;i++){
            temp = temp + arr[i];
        }
        return temp;
    }



    /**
     * 把16进制字符串转换成字节数组
     * @param hex
     * @return byte[]
     */
    public static byte[] hexStringToByte(String hex) {
        int len = (hex.length() / 2);
        byte[] result = new byte[len];
        char[] achar = hex.toCharArray();
        for (int i = 0; i < len; i++) {
            int pos = i * 2;
            result[i] = (byte) (toByte(achar[pos]) << 4 | toByte(achar[pos + 1]));
        }
        return result;
    }
    private static int toByte(char c) {
        byte b = (byte) "0123456789ABCDEF".indexOf(c);
        return b;
    }
    
    /** 
     * @param data1 
     * @param data2 
     * @return data1 与 data2拼接的结果 
     */  
    public static byte[] addBytes(byte[] data1, byte[] data2) {  
        byte[] data3 = new byte[data1.length + data2.length];  
        System.arraycopy(data1, 0, data3, 0, data1.length);  
        System.arraycopy(data2, 0, data3, data1.length, data2.length);  
        return data3;  
      
    }


/**
	 * convert byte[] to HexString
	 * 
	 * @param bArray
	 * @param length
	 * @return
	 */
	public static String bytesToHexString(byte[] bArray, int length){
		StringBuffer sb = new StringBuffer(length);
		String sTemp;
		for (int i = 0; i < length; i++) 
		{
			sTemp = Integer.toHexString(0xFF & bArray[i]);
			if (sTemp.length() < 2)
				sb.append(0);
			sb.append(sTemp.toUpperCase());
		}
		return sb.toString();
	}

    public static void main(String[] args) {
//        byte[] bytes = hexStringToByte(str);
    	String ip = "255255255255";
    	
        System.out.println(toHexL(ip,6));
        System.out.println(toHex(8379,2));
        System.out.println(Integer.valueOf("BB",16));
    }



}
